<script setup>
import coachCourseApi from "@/api/coachCourse.js";
import coachApi from "@/api/coach.js";
import {ref, computed, onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {
    Delete,
    Edit,
    Upload,
    Download,
    Plus,
    User
} from '@element-plus/icons-vue'
import {useTokenStore} from '@/store/token.js'

//数据表格
const list = ref([])
const total = ref(0)
//分页信息和搜索条件
const courseQuery = ref({
    name: '',
    page: 1,
    limit: 10
})

//教练信息
const tokenStore = useTokenStore();
const currentCoach = ref({
    id: null,
    name: '当前教练',
    phone: '',
    email: ''
})

//课程统计信息
const courseStats = computed(() => {
    const totalCourses = list.value.length
    const activeCourses = list.value.filter(course => course.status === 1).length
    const inactiveCourses = list.value.filter(course => course.status === 0).length
    return {
        total: totalCourses,
        active: activeCourses,
        inactive: inactiveCourses
    }
})

const loadData = () => {
    coachCourseApi.list(courseQuery.value).then(result => {
        if (result.code == 0) {
            list.value = result.data.records
            total.value = result.data.total
        } else {
            ElMessage.error(result.msg || '获取课程列表失败')
        }
    }).catch(error => {
        console.error('获取课程列表失败:', error)
        ElMessage.error('获取课程列表失败，请检查网络连接')
    })
}

//获取当前教练信息
const getCurrentCoachInfo = () => {
    coachApi.getCurrentCoachInfo().then(result => {
        if (result.code == 0) {
            currentCoach.value = result.data
            // 将教练ID存储到tokenStore中
            if (result.data && result.data.id) {
                tokenStore.setCoachId(result.data.id)
            }
        } else {
            ElMessage.error(result.msg || '获取教练信息失败')
            // 使用默认值
            currentCoach.value = {
                id: null,
                name: '当前教练',
                phone: '',
                email: ''
            }
        }
    }).catch(error => {
        console.error('获取教练信息失败:', error)
        ElMessage.error('获取教练信息失败，请检查网络连接')
        // 使用默认值
        currentCoach.value = {
            id: null,
            name: '当前教练',
            phone: '',
            email: ''
        }
    })
}

//组件挂载时获取数据
onMounted(() => {
    getCurrentCoachInfo()
    loadData()
})

const onSearch = () => {
    courseQuery.value.page = 1
    loadData()
}

const reset = () => {
    courseQuery.value.name = ''
    loadData()
}

//根据ID删除
const deleteById = (id) => {
    ElMessageBox.confirm(
        '您确认要删除吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            coachCourseApi.deleteById(id).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
}

//批量删除
const ids = ref([])
const handleSelectionChange = (rows) => {
    console.log('多选', rows)
    ids.value = rows.map(row => row.id)
    console.log(ids.value)
}
const deleteAll = () => {
    ElMessageBox.confirm(
        '您确认要删除吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            coachCourseApi.deleteAll(ids.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
}

//添加、编辑
const dialogFormVisible = ref(false)
const course = ref({
    length:1,
    maxCount:5
})
const showAddDialog = () => {
    course.value = {
        length:1,
        maxCount:5
    }
    dialogFormVisible.value = true
}

const showUpdateDialog = (id) => {
    dialogFormVisible.value = true
    course.value = {
        length:1,
        maxCount:5
    }
    coachCourseApi.selectById(id).then(result => {
        if (result.code == 0) {
            course.value = result.data
        }
    })
}

const addOrUpdate = () => {
    if (course.value.id) {
        coachCourseApi.update(course.value).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
                dialogFormVisible.value = false
                loadData()
            } else {
                ElMessage.error(result.msg)
            }
        })
    } else {
        coachCourseApi.add(course.value).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
                dialogFormVisible.value = false
                loadData()
            } else {
                ElMessage.error(result.msg)
            }
        })
    }
}

// el-switch状态切换
const handleSwitchChange = (row) => {
    console.log(row)
    const course = {}
    course.id = row.id
    course.status = row.status
    coachCourseApi.update(course).then(result => {
        if (result.code == 0) {
            ElMessage.success(result.msg);
        } else {
            ElMessage.error(result.msg)
        }
    })
}

//图片上传
const handleAvatarSuccess = (result) => {
    course.value.image = result.data
}

const headers = ref({
    //携带token传递到后端
    Authorization: tokenStore.token
});

//导入、导出excel
const exportExcel = () => {
    coachCourseApi.exportExcel().then((result) => {
        let blob = new Blob([result], { type: "application/xlsx" });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = "我的课程列表.xlsx"; // 重命名文件
        link.click();
        URL.revokeObjectURL(url);
    });
}

const importExcelSuccess = (result) => {
    if (result.code == 0) {
        ElMessage.success(result.msg)
        loadData()
    }
}
</script>

<template>
    <div class="coach-course-container">
        <!-- 教练信息卡片 -->
        <el-card class="coach-info-card" style="margin-bottom: 20px;">
            <template #header>
                <div class="coach-info-header">
                    <el-icon><User /></el-icon>
                    <span>教练信息</span>
                </div>
            </template>
            <div class="coach-info-content">
                <div class="coach-basic-info">
                    <el-descriptions :column="3" border>
                        <el-descriptions-item label="教练姓名">{{ currentCoach.name }}</el-descriptions-item>
                        <el-descriptions-item label="联系电话">{{ currentCoach.phone || '未设置' }}</el-descriptions-item>
                        <el-descriptions-item label="邮箱">{{ currentCoach.email || '未设置' }}</el-descriptions-item>
                    </el-descriptions>
                </div>
            </div>
        </el-card>

        <!-- 课程统计卡片 -->
        <el-card class="course-stats-card" style="margin-bottom: 20px;">
            <template #header>
                <div class="stats-header">
                    <el-icon><Plus /></el-icon>
                    <span>课程统计</span>
                </div>
            </template>
            <div class="stats-content">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <div class="stat-item total">
                            <div class="stat-number">{{ courseStats.total }}</div>
                            <div class="stat-label">总课程数</div>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="stat-item active">
                            <div class="stat-number">{{ courseStats.active }}</div>
                            <div class="stat-label">正常课程</div>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="stat-item inactive">
                            <div class="stat-number">{{ courseStats.inactive }}</div>
                            <div class="stat-label">停课课程</div>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-card>

        <!-- 课程管理卡片 -->
        <el-card class="course-management-card">
            <template #header>
                <div class="course-header">
                    <span>我的课程管理</span>
                    <div class="header-actions">
                        <el-button type="success" :icon="Plus" @click="showAddDialog">添加课程</el-button>
                        <el-button type="danger" :icon="Delete"@click="deleteAll">批量删除</el-button>
                        <el-button type="primary" :icon="Download" @click="exportExcel">导出Excel</el-button>
                        <el-upload
                            :icon="Upload"
                            class="inline-block"
                            multiple=""
                            method="post"
                            action="/api/coach/course/importExcel"
                            style="display:inline-block;margin-left: 12px"
                            accept=".xlsx,.xls"
                            :show-file-list="false"
                            :on-success="importExcelSuccess"
                            :headers="headers"
                            name="file">
                            <el-button type="primary" :icon="Upload">导入Excel</el-button>
                        </el-upload>
                    </div>
                </div>
            </template>
        <el-form :inline="true">
            <el-form-item label="课程名称">
                <el-input v-model="courseQuery.name" placeholder="请输入课程名称" clearable style="width: 200px"/>
            </el-form-item>
           
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="danger" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="name" label="课程名称"/>
            <el-table-column prop="time" label="课程时间" width="180"/>
            <el-table-column prop="length" label="课程时长"/>
            <el-table-column prop="maxCount" label="最大人数"/>
            <el-table-column prop="room" label="教室"/>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        :active-value="1"
                        :inactive-value="0"
                        active-text="正常"
                        inactive-text="停课"
                        inline-prompt
                        @change="handleSwitchChange(scope.row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="image" label="封面">
                <template #default="{row}">
                    <img :src="row.image" style="max-height: 40px; max-width: 120px;"/>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180px"/>
            <el-table-column align="center" width="200px" fixed="right" label="操作">
                <template #default="{ row }">
                    <el-button size="small" type="primary" @click="showUpdateDialog(row.id)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="courseQuery.page"
            v-model:page-size="courseQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
        </el-card>
    </div>

    <!--添加编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="course.id ? '编辑课程' : '添加课程'" width="60%" :lock-scroll="false">
        <el-form :model="course">
            <el-form-item label="课程名称" :label-width="80">
                <el-input v-model="course.name" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="开始时间" :label-width="80">
                <el-date-picker
                    v-model="course.time"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                />
            </el-form-item>
            <el-form-item label="课程时长" :label-width="80">
                <el-input-number :min="1" :max="100" step="1" v-model="course.length" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="教室" :label-width="80">
                <el-input v-model="course.room" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="最大人数" :label-width="80">
                <el-input-number :min="5" :max="100" step="5" v-model="course.maxCount" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="封面" :label-width="80">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :headers="headers">
                    <img v-if="course.image" :src="course.image" class="avatar"/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss">
.coach-course-container {
    padding: 20px;
}

.coach-info-header, .stats-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #409eff;
}

.course-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    color: #409eff;
}

.header-actions {
    display: flex;
    gap: 12px;
}

.coach-info-content {
    padding: 10px 0;
}

.stats-content {
    padding: 20px 0;
}

.stat-item {
    text-align: center;
    padding: 20px;
    border-radius: 8px;
    background: #f8f9fa;
    transition: all 0.3s ease;
    
    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    &.total {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }
    
    &.active {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        color: white;
    }
    
    &.inactive {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        color: white;
    }
}

.stat-number {
    font-size: 32px;
    font-weight: bold;
    margin-bottom: 8px;
}

.stat-label {
    font-size: 14px;
    opacity: 0.9;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
